package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 解析sqlMapConfig.xml
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 将配置文件进行解析，封装成configuration
     * @param inputStream
     * @return
     */
    public Configuration parse(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        // configuration
        Element rootElement = document.getRootElement();
        List<Element> selectNodes = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element selectNode : selectNodes) {
            String name = selectNode.attributeValue("name");
            String value = selectNode.attributeValue("value");

            // 将数据库配置信息封装到properties对象中
            properties.setProperty(name,value);
        }
        // 使用c3p0连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driver"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        // 设置数据库信息
        configuration.setDataSource(comboPooledDataSource);

        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String resource = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
            mapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }

}
